package com.fanqwz.hexieshe.presenter;

import android.util.Log;

import com.fanqwz.hexieshe.dagger.PerActivity;
import com.fanqwz.hexieshe.domain.Article;
import com.fanqwz.hexieshe.domain.Comment;
import com.fanqwz.hexieshe.domain.usercase.GetArticleUseCase;
import com.fanqwz.hexieshe.domain.usercase.GetCommentUseCase;
import com.fanqwz.hexieshe.mapper.DataMapper;
import com.fanqwz.hexieshe.view.ArticleView;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqw on 2017/7/4.
 */

@PerActivity
public class ArticlePresenter implements Presenter {
    private static final String TAG = ArticlePresenter.class.getSimpleName();
    private long id;
    private ArticleView articleView;

    @Inject
    GetArticleUseCase getArticleUseCase;
    @Inject
    GetCommentUseCase getCommentUseCase;

    @Inject
    public ArticlePresenter(GetArticleUseCase getArticleUseCase, GetCommentUseCase getCommentUseCase) {
        this.getArticleUseCase = getArticleUseCase;
        this.getCommentUseCase = getCommentUseCase;
    }

    public void setArticleID(long id) {
        this.id = id;
    }

    @Override
    public void create() {
    }

    @Override
    public void show() {
        articleView.prepare();
        getArticleUseCase.execute(new ArticleDisposableObserver(), new GetArticleUseCase.Params(id));
        getCommentUseCase.execute(new CommentsDisposableObserver(), new GetCommentUseCase.Params(id));
    }

    @Override
    public void hide() {

    }

    @Override
    public void destroy() {
    }

    public void setArticleView(ArticleView articleView) {
        this.articleView = articleView;
    }

    class ArticleDisposableObserver extends DisposableObserver<Article> {

        @Override
        public void onNext(Article value) {
            articleView.showArticle(DataMapper.transform(value));
        }

        @Override
        public void onError(Throwable e) {
            Log.e(TAG, "onError: ", e);
        }

        @Override
        public void onComplete() {
        }
    }

    class CommentsDisposableObserver extends DisposableObserver<List<Comment>> {

        @Override
        public void onNext(List<Comment> value) {
            if (articleView != null)
                articleView.showComments(DataMapper.transformComments(value));
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    }
}
